package cn.smart.epic.modular.system.service.impl;

import cn.smart.epic.common.exception.InvalidKaptchaException;
import cn.smart.epic.common.persistence.dao.UserMapper;
import cn.smart.epic.core.log.LogManager;
import cn.smart.epic.core.log.factory.LogTaskFactory;
import cn.smart.epic.core.shiro.ShiroKit;
import cn.smart.epic.core.shiro.ShiroUser;
import cn.smart.epic.core.util.CommonUtil;
import cn.smart.epic.core.util.ToolUtil;
import cn.smart.epic.modular.system.service.ILoginService;
import cn.smart.epic.modular.system.service.PermissionService;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;

import static cn.smart.epic.core.support.HttpKit.getIp;

/**
 * @Auther Uncle_Z
 * @date 2018/6/15 18:38
 * @Email:2545375@qq.com
 * @Descrition
 * @since 1.0
 */

@Service
public class LoginServiceImpl implements ILoginService {

    private Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionService permissionService;

    @Override
    public JSONObject authLogin(JSONObject jsonObject) {
        String username = jsonObject.getString("username").trim();
        String password = jsonObject.getString("password").trim();

        JSONObject returnData = new JSONObject();

        //验证验证码是否正确
        if(ToolUtil.getKaptchaOnOff()){
            String kaptcha = jsonObject.getString("kaptcha").trim();
            String code = jsonObject.getString("code").trim();
            if(ToolUtil.isEmpty(kaptcha) || !kaptcha.equals(code)){
                throw new InvalidKaptchaException();
            }
        }
        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password.toCharArray());
        try{
            currentUser.login(token);
            returnData.put("result","success");
            returnData.put("token",currentUser.getSession().getId());
            LogManager.me().executeLog(LogTaskFactory.loginLog(ShiroKit.getUser().getId(), getIp()));
        }catch (IncorrectCredentialsException  e){
            returnData.put("result","fail");
            returnData.put("msg","密码错误");
            logger.error(e.getMessage());
        }catch (LockedAccountException e){
            returnData.put("msg", "登录失败，该用户已被冻结");
        }catch (AuthenticationException e){
            returnData.put("msg", "该用户不存在");
        }

        return CommonUtil.successJson(returnData);
    }

    @Override
    public JSONObject getUser(String username) {
        return userMapper.getByName(username);
    }

    @Override
    public JSONObject getInfo() {
        ShiroUser shiroUser = ShiroKit.getUser();
        JSONObject returnData = new JSONObject();
        JSONObject userPermission;
        if (shiroUser.getRoleList().size() >0) {
            userPermission= permissionService.getUserPermission(shiroUser.getAccount(),shiroUser.getRoleList());
        }else{
            userPermission= permissionService.getUserPermission(shiroUser.getAccount(),Arrays.asList(0));
        }
        returnData.put("userPermission",userPermission);
        return CommonUtil.successJson(returnData);
    }

    @Override
    public JSONObject logout() {
        LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(),getIp()));
        ShiroKit.getSubject().logout();
        return CommonUtil.successJson();
    }
}
